import React, {Component} from 'react';

class PromiseTest extends Component {
    constructor(props) {
        super(props);
        this.state = {
            msg: ""
        }
    }

    componentDidMount() {
        this.init();
    }

    /**
     * 初始化
     */
    init = () => {
        const p3 = new Promise((resolve, reject) => {
            let {msg} = this.state;
            if (msg === "") {
                return reject(new Error("promise的错误")); //调用resolve或reject并不会终结 Promise 的参数函数的执行.
            }
            // 调用resolve或reject以后,Promise 的使命就完成了,后继操作应该放到then方法里面,
            // 而不应该直接写在resolve或reject的后面.所以,最好在它们前面加上return语句,这样就不会有意外.
            // reject(new Error("promise的错误")); //调用resolve或reject并不会终结 Promise 的参数函数的执行.
            console.log(2);
        }).then((res) => {
            console.log(res);
        }).catch((err) => {
            console.log(err);
        });
        p3;


        const p1 = new Promise((resolve, reject) => {
            setTimeout(() => reject(1), 3000)
        });
        const p2 = new Promise((resolve, reject) => {
            setTimeout(() => resolve(p1), 1000)
        });
        p2.then((result) => {
            console.log(result);
            console.log(p1);
            return p1;
        }).then(
            comments => console.log("resolved: ", comments),
            err => console.log("rejected: ", err)
        ).catch(() => {
            console.log(p1);
        }).finally(() => {
            console.log("finally");
        });


        /*const promiseOne = new Promise((resolve, reject) => {
            if (0) {
                resolve(promise);
            } else {
                reject(promise);
            }
        });
        const promise = new Promise((resolve, reject) => {
            if (0) {
                resolve(11)
            } else {
                reject(22)
            }
        });
        promiseOne.then((success) => {
            this.setState({
                msg: success
            })
        }, (err) => {
            this.setState({
                msg: err
            })
        })*/
    };

    render() {
        let {msg} = this.state;
        return (
            <div>
                {msg}
            </div>
        );
    }
}

export default PromiseTest